package com.dhcc.sds.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.entity.SdsQcincaseEntity;
import com.dhcc.sds.busi.entity.SdsQcincaseOperlogEntity;
import com.dhcc.sds.busi.service.ISdsQcincaseOperlogService;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import com.dhcc.sds.qzj.entity.DrgsInnerReportData;
import com.dhcc.sds.qzj.service.IDrgsInnerReportDataService;
import com.dhcc.sds.util.DateUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前置机上传国家平台记录信息
 */
@Service("qzjDataSyncTask")
public class QzjDataSyncTask {
    @Autowired
    private IDrgsInnerReportDataService drgsInnerReportDataService;
    @Autowired
    private ISdsQcincaseService sdsQcincaseService;
    @Autowired
    private ICdcEpisodeService cdcEpisodeService;
    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ISdsQcincaseOperlogService sdsQcincaseOperlogService;

    double all = 1;
    Double cur = (double) 0;

    /**
     * 同步昨日前置机上传国家平台数据信息
     */
    public void SyncReportData() {
        String yesterday = DateUtil.getDayDate(-1, "yyyy-MM-dd");//注意这个MM不要写成小写
        String startDate = yesterday + " 00:00:00";
        String endDate = yesterday + " 23:59:59";
        List<DrgsInnerReportData> reportDataList = drgsInnerReportDataService.findByReportTime(startDate, endDate);
        for (DrgsInnerReportData reportData : reportDataList) {
            String mrNo = reportData.getCaseId();
            String admDate = reportData.getDataTime();
            String reportDate = reportData.getReportTime();
            Integer reportState = reportData.getDataState();
            String reportMsg = reportData.getUploadErrReason();
            String diseaseType = reportData.getDiseaseTypes();
            // 获取病种信息
            SdsQcentityEntity diseaseInfo = sdsQcentityService.selectOne(new EntityWrapper<SdsQcentityEntity>().eq("abbrev", diseaseType));
            // 通过住院号和入院日期确定患者系统内就诊号
            CdcEpisodeEntity episodeEntity = cdcEpisodeService.selectOne(new EntityWrapper<CdcEpisodeEntity>().eq("mr_num", mrNo).like("adm_date", admDate));
            // 如果通过住院号和入院时间没取到，则取最近一次就诊出院的
            if (episodeEntity == null) {
                List<CdcEpisodeEntity> episodeEntityList = cdcEpisodeService.selectList(new EntityWrapper<CdcEpisodeEntity>().eq("mr_num", mrNo).isNotNull("dish_date").orderBy("dish_date", false));
                if (episodeEntityList.isEmpty()) {
                    continue;
                }
                episodeEntity = episodeEntityList.get(0);
            }
            // 获取入组记录
            SdsQcincaseEntity inCase = sdsQcincaseService.selectOne(new EntityWrapper<SdsQcincaseEntity>().eq("episode_id", episodeEntity.getId()).eq("entity_id", diseaseInfo.getId()).ne("state", "O"));
            if (inCase == null) continue;
            // 更新入组记录中国家平台上传信息
            inCase.setReportDate(DateUtil.parseTime(reportDate));
            inCase.setReportState(reportState);
            inCase.setReportMsg(reportMsg);
            inCase.updateById();
        }
    }

    public void ResetQzjStatus() {
        // 获取前置机地址
        String qzjPath = CdcConfigCache.me().getValueByKey("SDS", "SDserver");
        // 创建httpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 调用execute,返回response
        CloseableHttpResponse response = null;
        try {
            String qzjHost = new java.net.URL(qzjPath).getHost();
            // 创建请求方法的实例，并指定请求URL
            String url = "http://" + qzjHost + ":8711/jump?diseaseTypes=all";
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json;charset=utf8");
            response = client.execute(post);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void SynPatientInfo(Map<String, Object> params) {
        String startDate = params.get("startDate").toString();
        String endDate = params.get("endDate").toString();
        List<DrgsInnerReportData> reportDataList = drgsInnerReportDataService.findByReportTime(startDate, endDate);
        all = reportDataList.size();
        cur = (double) 0;
        for (DrgsInnerReportData reportData : reportDataList) {
            cur++;
            String mrNo = reportData.getCaseId();
            String admDate = reportData.getDataTime();
            String reportDate = reportData.getReportTime();
            Integer reportState = reportData.getDataState();
            String reportMsg = reportData.getUploadErrReason();
            String diseaseType = reportData.getDiseaseTypes();
            // 获取病种信息
            SdsQcentityEntity diseaseInfo = sdsQcentityService.selectOne(new EntityWrapper<SdsQcentityEntity>().eq("abbrev", diseaseType));
            // 通过住院号和出院日期确定患者系统内就诊号
            CdcEpisodeEntity episodeEntity = cdcEpisodeService.selectOne(new EntityWrapper<CdcEpisodeEntity>().eq("mr_num", mrNo).like("adm_date", admDate));
            // 如果通过住院号和入院时间没取到，则取最近一次就诊出院的
            if (episodeEntity == null) {
                continue;
                /*List<CdcEpisodeEntity> episodeEntityList = cdcEpisodeService.selectList(new EntityWrapper<CdcEpisodeEntity>().eq("mr_num", mrNo).isNotNull("dish_date").orderBy("dish_date", false));
                if (episodeEntityList.isEmpty()) {
                    continue;
                }
                episodeEntity = episodeEntityList.get(0);*/

            }
            // 获取入组记录
            SdsQcincaseEntity inCase = sdsQcincaseService.selectOne(new EntityWrapper<SdsQcincaseEntity>().eq("episode_id", episodeEntity.getId()).eq("entity_id", diseaseInfo.getId()).ne("state", "O"));
            if (inCase == null) continue;
            // 更新入组记录中国家平台上传信息
            inCase.setState("Up");
            inCase.setGroupStatus("SysRec");
            inCase.setFillingStatus("Submit");
            inCase.setReportStatus("Up");
            inCase.setReportDate(DateUtil.parseTime(reportDate));
            inCase.setReportState(reportState);
            inCase.setReportMsg(reportMsg);
            inCase.updateById();
            // 增加日志记录
            SdsQcincaseOperlogEntity operlog = sdsQcincaseOperlogService.selectOne(new EntityWrapper<SdsQcincaseOperlogEntity>().eq("in_case_id", inCase.getId()).eq("oper_state", "Up"));
            if (operlog == null) {
                operlog = new SdsQcincaseOperlogEntity();
                operlog.setInCaseId(inCase.getId());
                operlog.setOperUser("系统同步");
                operlog.setOperState("Up");
                operlog.setOperResume(reportMsg);
                operlog.setOperDate(DateUtil.parseTime(reportDate));
                operlog.insert();
            }
        }
    }

    public Map<String, Object> getProcess() {
        Map<String, Object> state = new HashMap<String, Object>();
        if (all == 0) {//没有获取到数据
            state.put("v", "100");//值
            state.put("i", "none");//信息
        } else {
            if (cur < all) {//进行中
                DecimalFormat df = new DecimalFormat("0.00");
                state.put("v", df.format(cur / all * 100));//值
                state.put("i", "doing");//信息
            } else {
                state.put("v", "100");//值
                state.put("i", "done");//信息
            }
        }
        return state;
    }
}
